package com.thiswhyme.common.utils.codec;

import com.thiswhyme.common.expection.BusinessException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * @description: SM4加解密工具类
 * @author: thiswhyme
 * @date: 2021/4/14
 */
public class SM4Utils {

    private static final Logger log = LoggerFactory.getLogger(SM4Utils.class);

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";

    /**
     * 加密-ECB模式PKCS5Padding填充
     * @param key 密钥
     * @param data 待加密数据
     * @return
     */
    public static byte[] encrypt_ECB_Padding(byte[] key, byte[] data) {
        Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return doFinal(cipher, data);
    }

    /**
     * 解密-ECB模式PKCS5Padding填充
     * @param key 密钥
     * @param cipherText 加密的数据
     * @return
     */
    public static byte[] decrypt_ECB_Padding(byte[] key, byte[] cipherText) {
        Cipher cipher = generateECBCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return doFinal(cipher, cipherText);
    }

    /**
     * 加密-CBC模式PKCS5Padding填充
     * @param key 密钥
     * @param data 待加密数据
     * @return
     */
    public static byte[] encrypt_CBC_Padding(byte[] key, byte[] iv, byte[] data) {
        Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
        return doFinal(cipher, data);
    }

    /**
     * 解密-CBC模式PKCS5Padding填充
     * @param key 密钥
     * @param cipherText 加密的数据
     * @return
     */
    public static byte[] decrypt_CBC_Padding(byte[] key, byte[] iv, byte[] cipherText) {
        Cipher cipher = generateCBCCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
        return doFinal(cipher, cipherText);
    }

    /**
     * 加解密操作
     * @param cipher 密码算法
     * @param data 待加解密数据
     * @return
     */
    private static byte[] doFinal(Cipher cipher, byte[] data) {
        byte[] result;
        try {
            result = cipher.doFinal(data);
        } catch (Exception e) {
            log.error("生成SM4加/解密异常", e);
            throw new BusinessException("生成SM4加/解密异常");
        }
        return result;
    }

    /**
     * 生成ECB（输出反馈模式Output Feedback）模式密码算法
     * @param algorithmName 算法名
     * @param mode 加密/解密
     * @param key 密钥
     * @return
     */
    private static Cipher generateECBCipher(String algorithmName, int mode, byte[] key) {
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
            Key sm4Key = new SecretKeySpec(key, EncryptAlgorithm.SM4.name());
            cipher.init(mode, sm4Key);
        } catch (Exception e) {
            log.error("生成SM4-ECB模式算法异常", e);
            throw new BusinessException("生成SM4-ECB模式算法异常");
        }
        return cipher;
    }

    /**
     * 生成CBC（密文反馈模式 Cipher Feedback）模式密码算法
     * @param algorithmName 算法名
     * @param mode 加密/解密
     * @param key 密钥
     * @param iv
     * @return
     */
    private static Cipher generateCBCCipher(String algorithmName, int mode, byte[] key, byte[] iv) {
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
            Key sm4Key = new SecretKeySpec(key, EncryptAlgorithm.SM4.name());
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            cipher.init(mode, sm4Key, ivParameterSpec);
        } catch (Exception e) {
            log.error("生成SM4-CBC模式算法异常", e);
            throw new BusinessException("生成SM4-CBC模式算法异常");
        }
        return cipher;
    }
}
